<template>
  <el-form
    ref="formRef"
    v-loading="formLoading"
    :model="formData"
    :rules="formRules"
    label-width="120px"
  >
    <el-row :gutter="20">
      <el-col :span="8">
        <el-form-item label="询单型号" prop="product.model_name">
          <el-input
            v-model="formData.product.model_name"
            :min="0"
            controls-position="right"
            style="width: 100%"
            :disabled="true"
          />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="询单数量" prop="buyer_amount">
          <el-input-number
            v-model="formData.buyer_amount"
            :min="0"
            controls-position="right"
            style="width: 100%"
            :disabled="true"
          />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="商品价格" prop="product.price">
          <el-input
            v-model="formData.product.price"
            :min="0"
            controls-position="right"
            style="width: 100%"
            :disabled="true"
          />
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="买家留言" prop="buyer_remark">
          <el-input
            v-model="formData.buyer_remark"
            type="textarea"
            placeholder="请输入买家留言"
            :disabled="true"
            :rowl="1"
          />
        </el-form-item>
      </el-col>

      <!-- 仅在编辑状态下显示卖家信息 -->

      <el-col :span="12">
        <el-form-item label="确认数量" prop="seller_amount">
          <el-input-number
            v-model="formData.seller_amount"
            :min="0"
            controls-position="right"
            style="width: 100%"
          />
        </el-form-item>
      </el-col>

      <el-col :span="24">
        <el-form-item label="卖家回复" prop="seller_remark">
          <el-input
            v-model="formData.seller_remark"
            type="textarea"
            placeholder="请输入卖家回复"
          />
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="回复媒体" prop="seller_remark_media">
          <el-upload
            v-model:file-list="fileList"
            class="upload-media"
            action="#"
            :http-request="handleUpload"
            :before-upload="beforeUpload"
            :on-remove="handleRemove"
            :on-preview="handlePreview"
            list-type="picture-card"
            :auto-upload="true"
            :multiple="true"
            :limit="5"
          >
            <el-icon>
              <Plus />
            </el-icon>
            <template #tip>
              <div class="el-upload__tip">
                jpg/png/jpeg/gif/mp4/mov/avi/webm 文件，最多上传5个文件
              </div>
            </template>
            <template #file="{ file }">
              <div>
                <img
                  v-if="isImage(file.name)"
                  class="el-upload-list__item-thumbnail"
                  :src="file.url"
                  alt=""
                />
                <video
                  v-else-if="isVideo(file.name)"
                  class="el-upload-list__item-thumbnail"
                  controls
                >
                  <source :src="file.url" type="video/mp4" />
                  Your browser does not support the video tag.
                </video>
                <img
                  v-else
                  class="el-upload-list__item-thumbnail"
                  :src="file.url"
                  alt=""
                />
                <span class="el-upload-list__item-actions">
                  <span
                    class="el-upload-list__item-preview"
                    @click="handlePreview(file)"
                  >
                    <el-icon><zoom-in /></el-icon>
                  </span>
                  <span
                    class="el-upload-list__item-delete"
                    @click="handleRemove(file)"
                  >
                    <el-icon>
                      <Delete />
                    </el-icon>
                  </span>
                </span>
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from "vue";
import api from "@/api/seller/verify/spotcheck";
import { uploadFile } from "@/utils/upload";
import { ElMessage } from "element-plus";
import { Plus, ZoomIn, Delete } from "@element-plus/icons-vue";
defineOptions({
  name: "SpotCheckForm"
});

const props = defineProps({
  id: {
    type: String,
    default: ""
  },
  visible: {
    type: Boolean,
    default: false
  },
  title: {
    type: String,
    default: ""
  }
});

const emit = defineEmits(["update:visible"]);

const formRef = ref();
const formLoading = ref(false);
const previewVisible = ref(false);
const previewUrl = ref("");
const previewTitle = ref("");
const previewFile = ref({ name: "" });
// 文件列表
const fileList = ref([]);

const formData = reactive({
  buyer_amount: 0,
  verify_code: "",
  buyer_remark: "",
  seller_remark: "",
  seller_remark_media: {
    img: [],
    video: []
  },
  seller_amount: 0,
  product: {
    model_name: "",
    price: 0
  }
});

const formRules = reactive({
  seller_amount: [
    { required: true, message: "请输入核实数量", trigger: "blur" }
  ]
});
// 监听媒体链接变化，更新文件列表
watch(
  () => formData.seller_remark_media,
  newVal => {
    if (newVal && typeof newVal === "object" && (newVal.img || newVal.video)) {
      const imgUrls = Array.isArray(newVal.img) ? newVal.img : [];
      const videoUrls = Array.isArray(newVal.video) ? newVal.video : [];

      // 合并所有媒体文件
      const allUrls = [...imgUrls, ...videoUrls];
      fileList.value = allUrls.map((url, index) => ({
        name: `media_${index + 1}.${getFileExtension(url)}`,
        url: url.trim()
      }));
    } else {
      fileList.value = [];
    }
  },
  { immediate: true }
);

// 获取文件扩展名
const getFileExtension = filename => {
  return filename.split(".").pop().toLowerCase();
};

// 判断是否为图片
const isImage = filename => {
  if (!filename) return false;
  const imageExtensions = ["jpg", "jpeg", "png", "gif"];
  const extension = getFileExtension(filename);
  return imageExtensions.includes(extension);
};

// 判断是否为视频
const isVideo = filename => {
  if (!filename) return false;
  const videoExtensions = ["mp4", "mov", "avi", "webm"];
  const extension = getFileExtension(filename);
  return videoExtensions.includes(extension);
};

// ... existing code ...
// 上传前检查
const beforeUpload = file => {
  // 使用文件扩展名检查而不是MIME类型
  const fileExtension = getFileExtension(file.name);
  const validImageExtensions = ["jpg", "jpeg", "png", "gif"];
  const validVideoExtensions = ["mp4", "mov", "avi", "webm"];

  const isValidType =
    validImageExtensions.includes(fileExtension) ||
    validVideoExtensions.includes(fileExtension);

  if (!isValidType) {
    ElMessage.error("只能上传 jpg/png/jpeg/gif/mp4/mov/avi/webm 格式的文件!");
    return false;
  }

  const maxSize = file.size / 1024 / 1024 < 50; // 50MB
  if (!maxSize) {
    ElMessage.error("文件大小不能超过 50MB!");
    return false;
  }

  return true;
};
// ... existing code ...

// ... existing code ...
// 处理上传
const handleUpload = options => {
  const { onSuccess, onError, onProgress, file } = options;

  return new Promise((resolve, reject) => {
    uploadFile(
      options,
      percent => {
        onProgress({ percent });
      },
      url => {
        // 更新表单数据 - 使用对象格式
        if (!formData.seller_remark_media) {
          formData.seller_remark_media = { img: [], video: [] };
        }

        // 判断文件类型并添加到对应数组
        if (isImage(file.name)) {
          if (!Array.isArray(formData.seller_remark_media.img)) {
            formData.seller_remark_media.img = [];
          }
          formData.seller_remark_media.img.push(url);
        } else if (isVideo(file.name)) {
          if (!Array.isArray(formData.seller_remark_media.video)) {
            formData.seller_remark_media.video = [];
          }
          formData.seller_remark_media.video.push(url);
        }

        onSuccess(url);
        resolve(url);
      },
      error => {
        onError(new Error(error));
        ElMessage.error(`上传失败: ${error}`);
        reject(new Error(error));
      }
    );
  });
};
// ... existing code ...
// ... existing code ...
// 处理文件移除
const handleRemove = file => {
  // 使用对象格式处理
  if (
    formData.seller_remark_media &&
    typeof formData.seller_remark_media === "object"
  ) {
    // 从img数组中移除
    if (Array.isArray(formData.seller_remark_media.img)) {
      const imgIndex = formData.seller_remark_media.img.findIndex(
        url => url === file.url
      );
      if (imgIndex > -1) {
        formData.seller_remark_media.img.splice(imgIndex, 1);
      }
    }

    // 从video数组中移除
    if (Array.isArray(formData.seller_remark_media.video)) {
      const videoIndex = formData.seller_remark_media.video.findIndex(
        url => url === file.url
      );
      if (videoIndex > -1) {
        formData.seller_remark_media.video.splice(videoIndex, 1);
      }
    }
  }

  // 更新文件列表
  const fileIndex = fileList.value.findIndex(
    item => item.uid === file.uid || item.url === file.url
  );
  if (fileIndex > -1) {
    fileList.value.splice(fileIndex, 1);
  }
};
// ... existing code ...

// 处理预览
const handlePreview = file => {
  previewUrl.value = file.url;
  previewFile.value = file;
  previewTitle.value = file.name;
  previewVisible.value = true;
};
// 提交表单
async function submitForm() {
  if (!formRef.value) return false;

  try {
    await formRef.value.validate();
    formLoading.value = true;
    const params = { ...formData };
    await api.update(props.id, params);
    return true;
  } catch (error) {
    console.error("保存失败:", error);
    return false;
  } finally {
    formLoading.value = false;
  }
}

// 获取详情
async function getDetail() {
  if (!props.id) return;
  try {
    formLoading.value = true;
    const { data } = await api.read(props.id);
    Object.keys(data).forEach(key => {
      if (key in formData) {
        formData[key] = data[key];
      }
    });
  } catch (error) {
    console.error("获取详情失败:", error);
  } finally {
    formLoading.value = false;
  }
}

defineExpose({
  submitForm
});

onMounted(() => {
  if (props.id) {
    getDetail();
  }
});
</script>
